package cn.dao.common.impl;

import cn.dao.common.EmployeeDao;
import cn.entity.Employee;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.sql.SQLException;

public class EmployeeDaoImpl extends HibernateDaoSupport implements EmployeeDao {
    public EmployeeDaoImpl(){
    }
    @Autowired
    public EmployeeDaoImpl(@Qualifier("sessionFactory")SessionFactory sessionFactory){
        this.setSessionFactory(sessionFactory);
    }

    @Override
    public Employee findEmpBySn(String sn) {
        return getHibernateTemplate().get(Employee.class,sn);
    }

    @Override
    public void save(Employee employee) {
//        Configuration cfg = new Configuration().configure();
//        SessionFactory sessionFactory = cfg.buildSessionFactory();
//        Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
//        sessionFactory.getCurrentSession().save(sysEmployee);
//        tx.rollback();
        getHibernateTemplate().save(employee);
    }
    @Override
    public Employee findByPidAndDid(final Integer pid, final Integer did) {
        Employee employee = getHibernateTemplate().execute(new HibernateCallback<Employee>() {
            @Override
            public Employee doInHibernate(Session session) throws HibernateException, SQLException {
                String hql = "from Employee e  where  e.sysPosition=?";
                if (did!=null){
                    hql+= " and e.sysDepartment .id=?";
                }
                Query query = session.createQuery(hql).setInteger(0,pid);
                if (did!=null){
                    query.setInteger(1,did);
                }

                return (Employee) query.uniqueResult();
            }
        });
        return employee;
    }
}
